using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Zsa.Emulation.Cartridge;
using Zsa.Emulation.CNes.UI;
using NesHostForm = Zsa.Emulation.HostForm;
using Zsa.Emulation.Config;
using System.IO;

namespace Zsa.Emulation.CNes
{
    /// <summary>
    /// The main form.
    /// </summary>
    public partial class MainForm : NesHostForm
    {
        /// <summary>
        /// The options form.
        /// </summary>
        private OptionsForm _OptionsForm;

        #region Constructor
        /// <summary>
        /// Region Constructor
        /// </summary>
        public MainForm()
        {
            InitializeComponent();
            
        }
        #endregion Constructor


        #region Methods

        #region Menu Event Handlers
        /// <summary>
        /// Handles the Click event of the openToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CartridgeFileInfo _CartInfo = null;
            using (RomBrowserForm _RomBrowser = new RomBrowserForm())
            {
                if (_RomBrowser.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                _CartInfo = _RomBrowser.SelectedCart;
                object _Obj = _RomBrowser.DirectoryKey;
                if (_Obj != null)
                {
                    _TestPath = _Obj.ToString();
                }
            }
            
            LoadGame(_CartInfo);
        }


        /// <summary>
        /// Handles the Click event of the optionsToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OptionsForm.OptionTabs _OptionTab = OptionsForm.OptionTabs.General;
            if ( sender == generalToolStripMenuItem )
            {
                _OptionTab = OptionsForm.OptionTabs.General;
            }
            else if (sender == videoToolStripMenuItem)
            {
                _OptionTab = OptionsForm.OptionTabs.Video;
            }
            else if (sender == soundToolStripMenuItem)
            {
                
            }
            else if (sender == gameDatabaseToolStripMenuItem)
            {
            }
            else
            {
                throw new Exception();
            }
            
            if (_OptionsForm == null)
            {
                _OptionsForm = new OptionsForm();
                _OptionsForm.OptionTab = _OptionTab;
                _OptionsForm.Show(this);
            }
            else
            {
                _OptionsForm.Focus();
            }
        }


        /// <summary>
        /// Handles the Click event of the startToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        private void startToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }
        #endregion Menu Event Handlers


        ///// <summary>
        ///// Loads the game.
        ///// </summary>
        ///// <param name="game">The game.</param>
        ///// <param name="settings">The settings.</param>
        ///// <param name="renderSettings">The render settings.</param>
        ///// <param name="tabPage">The tab page.</param>
        public void LoadGame(CartridgeFileInfo game)
        {
            try
            {
                if (NesHost.HostedDevices.Count > 0)
                {
                    OnClose(NesHost.HostedDevices[0]);
                    NesHost.HostedDevices.RemoveAt(0);
                }
                if (tabControl1.TabCount < 1)
                {
                    tabControl1.TabPages.Add("Device Output");
                }
                
                NesMachineHost _Host = this.NesHost.CreateMachine(NesConfigurationManager.Default,
                    tabControl1.TabPages[0], Zsa.Emulation.Render.MachineHostFlags.Default);
                _Host.LoadCartridge(game);
                _Host.Start();

                OnLoad(_Host);
            }
            catch (Exception excep)
            {
                throw;
            }
        }



        #endregion Methods

        #region Test Stuff
        CartridgeFileInfoCollection _Carts;
        int _CartIndex;
        private void toolStripSplitButton1_ButtonClick(object sender, EventArgs e)
        {
            GetTestCarts();
        }

        string _TestPath = Config.NesConfigurationManager.Profiles.LastRomFilePath;
        private void GetTestCarts()
        {
            

            List<string> _Files =
    new List<string>(
    Directory.GetFiles(_TestPath, "*.nes", SearchOption.TopDirectoryOnly)
    );

            // Add the nes file extensions
            _Files.AddRange(
                Directory.GetFiles(_TestPath, "*.rom", SearchOption.TopDirectoryOnly)
                );
            _Carts = DumpManager.ScanFiles(_Files.ToArray(), null);
            //CartridgeFileInfoCollection _CartInfo = DumpManager.ScanFiles(_Files.ToArray(), null);

        }
        private void toolStripSplitButtonTestNextRom_ButtonClick(object sender, EventArgs e)
        {
            if (_Carts == null)
            {
                GetTestCarts();
                _CartIndex = -1;
            }

            if (_Carts.Count == 0)
            {
                _CartIndex = 0;
                return;
            }

            _CartIndex++;

            if (_CartIndex < 0 || _CartIndex > _Carts.Count - 1)
            {
                _CartIndex = 0;
            }
            
            LoadGame(_Carts[_CartIndex]);
            
        }

        private void toolStripSplitButton1_ButtonClick_1(object sender, EventArgs e)
        {
            if (_Carts == null)
            {
                GetTestCarts();
                _CartIndex = _Carts.Count;
            }

            if (_Carts.Count == 0)
            {
                return;
            }

            _CartIndex--;
            if (_CartIndex < 0 || _CartIndex > _Carts.Count)
            {
                _CartIndex = _Carts.Count - 1;
            }
            
            LoadGame(_Carts[_CartIndex]);
            
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (NesHost.HostedDevices.Count > 0)
            {
                toolStripStatusLabel2.Text = "Fps : " +
                    NesHost.HostedDevices[0].Fps.ToString();
            }
        }

        #endregion Test Stuff

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (NesHost.HostedDevices.Count > 0)
            {
                OnClose(NesHost.HostedDevices[0]);
                NesHost.HostedDevices.RemoveAt(0);
            }
        }

        private void OnLoad(NesMachineHost machineHost)
        {
            if (machineHost != null)
            {
                toolStripStatusLabelGame.Text = machineHost.CurrentCart.FileName;
                toolStripStatusLabel2.Text = "Fps : 0";
            }
        }

        private void OnClose(NesMachineHost machineHost)
        {
            toolStripStatusLabelGame.Text = "None";
            toolStripStatusLabel2.Text = "Fps : 0";
            if (machineHost != null)
            {
                machineHost.Close();
            }

        }



    }
}